package software_construction.calcu_05_demo.io;

import software_construction.calcu_05_demo.equation.AddEquation;
import software_construction.calcu_05_demo.equation.Equation;
import software_construction.calcu_05_demo.equation.Exercise;
import software_construction.calcu_05_demo.equation.SubEquation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class ExerciseFileDao {
    public void writeExerciseToFile(Exercise exercise, String filePath) {
        File file = new File(filePath);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            ArrayList<Equation> equationList = exercise.getEquationList();
            for (int i = 0; i < equationList.size(); i++) {
                if (i == equationList.size() - 1) {
                    fileWriter.append(equationList.get(i).toString());
                } else {
                    fileWriter.append(equationList.get(i) + "  ," + "\r");
                }
            }
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Exercise readExerciseFromFile(String filePath) {
        File file = new File(filePath);
        Exercise exercise = new Exercise();
        String equationStr;
        Scanner scanner = null;
        try {
            scanner = new Scanner(file);
            scanner.useDelimiter(",");
            while (scanner.hasNext()) {
                equationStr = scanner.next().replaceAll("\\s", "");
                if (equationStr.contains("+")) {
                    exercise.getEquationList().add(new AddEquation(equationStr));
//                    ArrayList<Equation> equationList = exercise.getEquationList();
//                    AddEquation addEquation=new AddEquation(equationStr);
//                    equationList.add(addEquation);

                }else {
                    exercise.getEquationList().add(new SubEquation(equationStr));

                }


            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            scanner.close();
        }
        return exercise;
    }
}
